import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/Login')
  },
  {
    path: '/minor',
    name: 'Minor',
    component: () => import('@/components/Minor'),
    children: [
      { path: '/minor/forget', name: 'Forget', component: () => import('@/views/login/Forget') },
      { path: '/minor/register', name: 'Register', component: () => import('@/views/login/Register') }
    ]
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/components/Home'),
    redirect: !JSON.parse(localStorage.getItem('active')) ? '/home/index' : JSON.parse(localStorage.getItem('active')).activeIndex,
    children: [
      { path: '/home/index', name: 'Index', component: () => import('@/views/home/Index') },
      { path: '/home/menu', name: 'Menu', component: () => import('@/views/home/Menu') },
      { path: '/home/monitor', name: 'Monitor', component: () => import('@/components/Monitor') }
    ]
  },
  {
    path: '/tools',
    name: 'Tools',
    component: () => import('@/components/Tools'),
    children: [
      { path: '/tools/password', name: 'Password', component: () => import('@/views/tools/Password') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由守卫
router.beforeEach((to, from, next) => {
  // to：将要访问的路径、from：从哪个路径跳转过来、next：是一个函数表示放行
  if (to.path === '/login' || to.path === '/minor/forget' || to.path === '/minor/register') return next()
  // 获取token
  const token = localStorage.getItem('token')
  if (!token) return next('/login')
  next()
})

export default router
